# -*- coding: utf-8 -*-
import KBEngine
import IKernel
import time
import random
import xml.dom.minidom
import ConstDef

from KBEDebug import *

class ItemModule:
	def __init__(self):
		self.itemsCfg = {}

	def init(self, isReload):
		self.loadRes()

	def end(self):
		pass

	# 加载资源
	def loadRes(self):
		self.itemsCfg = {}

		#打开xml文档
		allItemsPatchXml = KBEngine.getResFullPath("cfg/items/all_items_path.xml")
		domPath = xml.dom.minidom.parse(allItemsPatchXml)
		#得到文档元素对象
		rootFileNames = domPath.documentElement

		propFileNames = rootFileNames.getElementsByTagName("property")
		for propFileName in propFileNames :
			filename = propFileName.getAttribute("path")

			path = KBEngine.getResFullPath("cfg/items/" + filename)
			#打开xml文档
			domItems = xml.dom.minidom.parse(path)
			#得到文档元素对象
			rootItems = domItems.documentElement

			propItems = rootItems.getElementsByTagName("property")
			for propItem in propItems :
				id = int(propItem.getAttribute("id"));
				if id == 0 :
					ERROR_MSG("filename=%s has item id=0" % (filename))
					continue
				elif self.itemsCfg.get(id) != None:
					ERROR_MSG("The id=%d are duplicated." % (id))
					assert(False)

				itemCfg = {}
				for itemPropName, v in propItem._attrs.items():
					value = v.value
					if value.isdigit():
						value = int(v.value)
					itemCfg[itemPropName] = value

				self.itemsCfg[id] = itemCfg

	# 通过 itemID 获取物品数量
	def getItemNum(self, entityID, itemID):
		entity = KBEngine.entities.get(entityID)

		itemCfg = self.itemsCfg[itemID]
		# 是否可堆叠
		stackable = itemCfg.get("stackable")
		hasNum = 0

		for itemUid, item in entity.itemBag.items():
			if item["id"] != itemID:
				continue

			if stackable != None and stackable > 1: # 是可堆叠物品
				return item["num"];
			else:
				hasNum += 1

		return hasNum

	# 获取同一物品类型的所有数量
	def getSameTypeItemNum(self, entityID, itemType):
		entity = KBEngine.entities.get(entityID)

		hasNum = 0
		for itemUid, item in entity.itemBag.items():
			if item["itemType"] != itemType:
				continue

			hasNum += 1

		return hasNum

	def addItem(self, entityID, itemID, itemNum, addLogType):
		"""
		添加物品，如果脚本事件名(物品表中的scriptName字段)不为空，触发 addAfter 事件
		@entityID 实体id
		@itemID 物品id
		@itemNum 增加的数量
		@addLogType 增加物品的类型, 具体意思在 LogDef 里面
		"""
		entity = KBEngine.entities.get(entityID)

		itemCfg = self.itemsCfg[itemID]
		if itemCfg == None:
			return False

		# 是否可堆叠
		stackable = itemCfg.get("stackable")
		# 剩余要添加的物品数量
		surplusAddNum = itemNum
		while surplusAddNum > 0:
			# 背包中同一类型物品(不可堆叠的话,为空)
			bagItem = None
			# 将要增加的数量
			willAddNum = 0
			if stackable != None and stackable == 1: # 是可堆叠物品
				# 可叠加物品,一次性加完，不考虑物品数量达到上限
				willAddNum = surplusAddNum
				for itemUid, item in entity.itemBag.items():
					if item["id"] != itemID:
						continue
					bagItem = item
					break
			else:
				#不可堆叠物品需要1件1件的加
				willAddNum = 1

			itemUid = 0
			if bagItem != None:
				bagItem["num"] = bagItem["num"] + willAddNum
				itemUid = bagItem["uid"]
			else:
				itemUid = KBEngine.genUUID64()
				bagItem = {}
				bagItem["uid"] = itemUid
				bagItem["id"] = itemID
				bagItem["num"] = willAddNum
				entity.itemBag[itemUid] = bagItem
				#如果还有其他属性的话，就在事件回调中，增加各个功能的独自特有属性了

			surplusAddNum -= willAddNum

		# todo 日志模块待添加
		# ModuleMgr.Instance().getModule("LogModule").addItemLog(entity, addLogType, [itemID, itemNum])
		return True

	def subItem(self, entityID, itemUid, itemID, itemNum, subLogType):
		"""
		调用函数前,各自逻辑模块,自己保证物品数量是否足够
		减少物品，如果脚本事件名(物品表中的scriptName字段)不为空，触发 subAfter 事件
		@entityID 实体id
		@itemUid 可堆叠物品的时候填0或者填对应uid都可以，不可堆叠物品必须填写
		@itemID 物品id
		@itemNum 减少的数量(不可堆叠物品,数量必须为1)
		@subLogType 增加物品的类型, 具体意思在 LogDef 里面
		"""
		itemCfg = self.itemsCfg[itemID]
		# 是否可堆叠
		stackable = itemCfg.get("stackable")
		if (stackable == None or stackable != 1) and (itemUid == 0 or itemNum != 1):
			# 不可堆叠物品必须传物品uid并且减少数量只能是1
			# 否则逻辑就有错误了
			assert(False)
			return False

		entity = KBEngine.entities.get(entityID)
		bagItem = entity.itemBag.get(itemUid)
		if bagItem == None:
			#经过上面的判断后，这里肯定是可堆叠物品
			for itemUid, item in entity.itemBag.items():
				if item["id"] != itemID:
					continue
				bagItem = item
				break

		if bagItem == None:
			# 没有找到对应物品，需要报错
			ERROR_MSG("no found item itemID=%d" % (itemID))
			return False

		itemUid = bagItem["uid"]
		bagItem["num"] = bagItem["num"] - itemNum
		if bagItem["num"] == 0:
			entity.itemBag.pop(itemUid)

		# todo 日志模块待添加
		# ModuleMgr.Instance().getModule("LogModule").subItemLog(entity, subLogType, [itemID, itemNum])
		return True
































